#include <metal_stdlib>
using namespace metal;

// 顶点输入结构
struct VertexInput {
    float4 position [[attribute(0)]];
    float2 texCoord [[attribute(1)]];
};

// 顶点输出结构
struct VertexOutput {
    float4 position [[position]];
    float2 texCoord;
};

// 顶点着色器
vertex VertexOutput vertexShader(VertexInput input [[stage_in]]) {
    VertexOutput output;
    output.position = input.position;
    output.texCoord = input.texCoord;
    return output;
}

// 片段着色器
//fragment half4 fragmentShader(VertexOutput input [[stage_in]],
//                             texture2d<half> videoTexture [[texture(0)]]) {
//    constexpr sampler s(address::clamp_to_edge, filter::linear);
//    half4 color = videoTexture.sample(s, input.texCoord);
//    return color;
//}

// --------------------------
// 3. 片段着色器：明暗转透明度核心逻辑
// --------------------------
fragment half4 fragmentShader(
    VertexOutput in [[stage_in]],
    texture2d<half> tex [[texture(0)]], // 输入纹理（待处理的图片）
    sampler texSampler [[sampler(0)]] // 纹理采样器
) {
    
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    
    // 步骤1：采样原始纹理颜色（含RGB+Alpha，此处暂用RGB计算亮度）
    half4 originalColor = tex.sample(s, in.texCoord);
    
    // 步骤2：计算当前像素的亮度（明暗程度）→ 范围[0,1]
    half luminance = dot(originalColor.rgb, half3(0.299, 0.587, 0.114));
    // dot()：向量点积，等价于 0.299*R + 0.587*G + 0.114*B
    
    // 步骤3：亮度映射为Alpha（根据invert参数控制方向）
    half alpha;
 
    alpha = luminance; // 正常：亮→不透（luminance=1→alpha=1），暗→透（luminance=0→alpha=0）
    
    
    // 步骤4：输出结果（保留RGB原始颜色，仅替换Alpha）
    return half4(originalColor.rgb, alpha);
}

// 提取图像的片段着色器
fragment half4 extractFragmentShader(
    VertexOutput input [[stage_in]],
    texture2d<half> sourceTexture [[texture(0)]],
    constant float2x2 &texCoordRange [[buffer(0)]]
) {
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    
    // 调整纹理坐标以提取指定区域
    float2 minTexCoord = texCoordRange[0];
    float2 maxTexCoord = texCoordRange[1];
    float2 adjustedTexCoord = minTexCoord + (input.texCoord * (maxTexCoord - minTexCoord));
    
//    return sourceTexture.sample(s, input.texCoord);
    return sourceTexture.sample(s, adjustedTexCoord);
}

// 应用透明度的片段着色器
fragment half4 alphaFragmentShader(
    VertexOutput input [[stage_in]],
    texture2d<half> originalTexture [[texture(0)]],
    texture2d<half> maskTexture [[texture(1)]]
) {
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    
    half4 originalColor = originalTexture.sample(s, input.texCoord);
    half4 maskColor = maskTexture.sample(s, input.texCoord);
    
    // 使用通道图的灰度值作为透明度
    half alpha = (maskColor.r + maskColor.g + maskColor.b) / 3.0;
    return half4(originalColor.rgb, alpha);
}
